<!--
 * @Description: 活动商品添加页面
 * @Author: liyujie
 * @Date: 2020/02/04
 * @Last Modified by: liyujie
 * @Last Modified time: 2020/02/04
-->
<template>
    <div class="wrapper">
        <div class="page">
            <!-- header -->
            <div class="header">
                <div class="header-title">
                    批量添加商品
                </div>
                <div class="option-btn">
                    <el-button
                        type="primary"
                        size="medium"
                        @click="showSettingDialog"
                    >
                        批量设置
                    </el-button>
                    <el-button
                        type="primary"
                        size="medium"
                        @click="handleSelectAll"
                    >
                        {{ isSelectAll ? '取消全选' : '全选' }}
                    </el-button>
                </div>
            </div>
            <!-- /header -->
            <!-- table -->
            <el-form
                :model="ruleForm"
                :rules="rules"
                style="height: calc(100% -  100px)"
                ref="ruleForm"
            >
                <el-table
                    :data="ruleForm.tableData"
                    height="100%"
                    style="width: 100%;"
                    ref="table"
                >
                    <el-table-column
                        align="center"
                        width="80"
                    >
                        <template slot-scope="scope">
                            <div
                                v-for="item in scope.row.product_list"
                                :key="item.product_no"
                                class="table-item"
                            >
                                <el-checkbox
                                    v-model="item.check_status"
                                    :true-label="1"
                                    :false-label="0"
                                    @change="handleSelectChange"
                                />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="商品缩略图"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <img
                                :src="scope.row.goods_cover"
                                style="width: 60px"
                                @click="fnShowPreview(scope.row.goods_cover)"
                            >
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="goods_no"
                        label="商品编号"
                        show-overflow-tooltip
                        align="left"
                    />
                    <el-table-column
                        prop="goods_title"
                        label="商品标题"
                        show-overflow-tooltip
                        align="left"
                    />
                    <el-table-column
                        prop="shop_title"
                        label="商家名称"
                        show-overflow-tooltip
                        align="left"
                    />
                    <el-table-column
                        label="商品规格"
                        align="center"
                        width="300"
                    >
                        <template slot-scope="scope">
                            <div
                                class="table-item"
                                v-for="item in scope.row.product_list"
                                :key="item.product_no"
                            >
                                <span
                                    v-for="(option,i) in item.spec_list"
                                    :key="i"
                                    style="margin: 0 6px"
                                >
                                    {{ `${option.spec_name} : ${option.spec_value}` }}
                                </span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="售价"
                        show-overflow-tooltip
                        align="center"
                    >
                        <template slot-scope="scope">
                            <div
                                class="table-item"
                                v-for="item in scope.row.product_list"
                                :key="item.product_no"
                            >
                                ￥{{ item.product_price }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="团购价"
                        show-overflow-tooltip
                        align="center"
                    >
                        <template slot-scope="scope">
                            <div
                                class="table-item"
                                v-for="item in scope.row.product_list"
                                :key="item.product_no"
                            >
                                <el-button
                                    type="text"
                                    style="margin-top: -10px"
                                    v-if="scope.row.wholesale_info"
                                    @click="getGroupPrice(scope.row, item)"
                                >
                                    查看
                                </el-button>
                                <div v-else>--</div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="吃货节价格"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <div
                                class="table-item"
                                v-for="(item,index) in scope.row.product_list"
                                :key="item.product_no"
                            >
                                <el-form-item
                                    :prop="`tableData.${scope.$index}.product_list[${index}]`"
                                    :rules="rules.activity_price"
                                >
                                    <el-input
                                        v-model="item.activity_price"
                                        clearable
                                        size="small"
                                        :disabled="!scope.row.product_list[index].check_status"
                                        @click.native="clickDisableInput(scope.row, scope.$index, index)"
                                    />
                                </el-form-item>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="库存"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <div
                                class="table-item"
                                v-for="item in scope.row.product_list"
                                :key="item.product_no"
                            >
                                {{ item.product_stock }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="优惠力度"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <div
                                class="cursor-font"
                                v-if="scope.row.reduction_info"
                            >
                                <el-popover
                                    placement="left"
                                    :width="scope.row.reduction_info.list.length == 0 ? 120 :'auto'"
                                >
                                    <div
                                        v-if="scope.row.reduction_info.list.length > 0"
                                        :style="{width: '100%', textAlign: 'center', display: 'flex', flexDirection: 'column'}"
                                    >
                                        <div :style="{height: '28px', display: scope.row.reduction_info.list.length > 1 ? 'flex' : '', alignItems: 'center'}">
                                            <div
                                                v-for="(item, index) in scope.row.reduction_info.list"
                                                :key="index"
                                            >
                                                <div
                                                    v-if="index <= 2"
                                                    class="reduction_price"
                                                    :style="{color: scope.row.reduction_info.reduction_type == 2 ? '#FF3030' : '#FDA623', borderColor: scope.row.reduction_info.reduction_type == 2 ? '#FF3030' : '#FDA623', margin: index == 1 ? (scope.row.reduction_info.list.length == 2 ? '0 0 0 12px' : '12px') : '0'}"
                                                >
                                                    满{{ item.require_num }}{{ scope.row.reduction_info.reduction_type == 2 ? '' : '件' }}减{{ item.reduction_price }}
                                                </div>
                                            </div>
                                        </div>
                                        <div
                                            :style="{height: '28px', display: 'flex', alignItems: 'center', marginTop: '18px'}"
                                            v-if="scope.row.reduction_info.list.length > 3"
                                        >
                                            <div
                                                v-for="(item, index) in scope.row.reduction_info.list"
                                                :key="index"
                                            >
                                                <div
                                                    v-if="index > 2"
                                                    class="reduction_price"
                                                    :style="{color: scope.row.reduction_info.reduction_type == 2 ? '#FF3030' : '#FDA623', borderColor: scope.row.reduction_info.reduction_type == 2 ? '#FF3030' : '#FDA623', margin: index == 4 ? (scope.row.reduction_info.list.length == 5 ? '0 0 0 12px' : '12px') : '0'}"
                                                >
                                                    满{{ item.require_num }}{{ scope.row.reduction_info.reduction_type == 2 ? '' : '件' }}减{{ item.reduction_price }}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div
                                        v-else
                                        :style="{width: '100%', textAlign: 'center'}"
                                    >
                                        暂无数据
                                    </div>
                                    <el-button
                                        slot="reference"
                                        type="text"
                                    >
                                        查看
                                    </el-button>
                                </el-popover>
                            </div>
                            <div v-else>--</div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                @click="handleDelete(scope.$index)"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <!-- /table -->
            <div class="btn-group">
                <el-button
                    size="medium"
                    @click="handleCancel()"
                >
                    取消
                </el-button>
                <el-button
                    size="medium"
                    type="primary"
                    @click="handleSubmit()"
                >
                    完成
                </el-button>
            </div>
        </div>

        <el-dialog
            title="批量设置"
            :visible.sync="settingDialog"
            width="640px"
            :close-on-click-modal="false"
            @close="handleDialogClose"
        >
            <el-form
                :model="settingForm"
                :rules="rules"
                ref="settingForm"
                label-width="100px"
                style="width: 400px;margin-left: 50%;transform: translateX(-50%);"
                @submit.native.prevent
            >
                <el-form-item
                    label="吃货节价格"
                >
                    <el-input
                        v-model="settingForm.activity_price"
                        placeholder="吃货节价格"
                        size="medium"
                        clearable
                        @keydown.enter.native="handleBatchSetting"
                    />
                </el-form-item>
            </el-form>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    size="medium"
                    :style="{width: '120px', marginRight: '32px'}"
                    @click="settingDialog = false"
                >
                    取消
                </el-button>
                <el-button
                    type="primary"
                    size="medium"
                    :style="{width: '120px'}"
                    @click="handleBatchSetting"
                >
                    确认
                </el-button>
            </span>
        </el-dialog>

        <!--结果弹窗-->
        <el-dialog
            :visible.sync="resultDialog"
            width="396px"
            :close-on-click-modal="false"
            :show-close="false"
            custom-class="result-dialog"
        >
            <div class="result-view">
                <div class="result-icon">
                    <i class="el-icon-error"/>
                    <div>以下商品导入失败</div>
                </div>
                <div class="result-reason">
                    <div
                        class="reason-list"
                        v-if="resultReasonList.length"
                    >
                        <div
                            class="reason-value"
                            v-for="(item, index) in resultReasonList"
                            :key="index"
                        >
                            {{ item.msg }}
                        </div>
                    </div>
                </div>
            </div>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    size="medium"
                    :style="{width: '120px', marginRight: '24px'}"
                    @click="resultDialog = false"
                >
                    取消
                </el-button>
                <el-button
                    type="primary"
                    size="medium"
                    :style="{width: '120px'}"
                    @click="resultDialog = false"
                >
                    确认
                </el-button>
            </span>
        </el-dialog>

        <!-- 图片预览 -->
        <img-preview ref="preview"/>
        <!-- 团购价弹窗 -->
        <group-price-dialog
            ref="groupPriceDialog"
        />
    </div>
</template>

<script>
/**
 * 页面接收参数
 * @param goodsList - 所选商品列表
 */

import {back} from '@/mixin/back';
import imgPreview from '@/components/common/img-preview';
import GroupPriceDialog from '@/components/member-card/group-price-dialog';

export default {
    name: "ActiveGoodsAdd",
    data() {
        const validatePrice = (rule, value, callback) => {

            if(value.check_status && !value.activity_price) {
                callback(new Error('请输入活动价'));
            } else {
                callback();
            }
        };

        return {
            ruleForm: {
                tableData: [],
            },
            settingForm: {
                // 吃货节价格
                activity_price: '',
            },
            rules: {
                activity_price: [
                    {validator: validatePrice, trigger: 'blur'}
                ]
            },
            // 是否全选
            isSelectAll: false,
            // 设置弹窗
            settingDialog: false,
            // 选中的数据
            selection: [],
            resultDialog: false,
            resultReasonList: []
        };
    },
    mixins: [back],
    components: {
        imgPreview,
        GroupPriceDialog
    },
    mounted() {
        this.$store.commit('SET_HEADER', [{title: "APP后台"}, {title: '商城'}, {
            title: '审核商品',
            path: '/student/active-goods-verify'
        }, {title: '批量添加商品'}]);
        this.init();
    },

    methods: {

        init() {
            let goodsList = JSON.parse(this.$route.query.goodsList);

            goodsList.map(item => {
                item.product_list.map(subItem => {
                    subItem.check_status = 1;
                    subItem.activity_price = '';
                });
            });
            this.handleSelectAll();
            this.ruleForm.tableData = goodsList;
        },
        /**
         * 查看图片
         * @param   {String}    images      //单图预览
         * @param   {Array}     images      //多图预览
         */
        fnShowPreview(images) {
            if (images && Object.prototype.toString.call(images) == '[object String]') {
                this.$refs.preview.show([
                    images
                ]);
            } else if (images && Object.prototype.toString.call(images) == '[object Array]') {
                this.$refs.preview.show(images);
            } else {
                this.$message({
                    type: 'warning',
                    message: '图片类型错误'
                });
            }
        },
        /**
         * 取消返回列表
         */
        handleCancel() {
            this.$confirm('返回后将不会保存您所修改的内容,是否返回?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$router.push({
                    path: '/student/active-goods-verify'
                });
            });
        },

        /**
         * 提交数据
         */
        handleSubmit() {

            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    let tableData = [...this.ruleForm.tableData];
                    let params = {
                        goods_json: JSON.stringify(tableData)
                    };

                    this.$post('/student/activity%5Ca20210517_import_list', params, resp => {
                        if (resp.code === 1) {
                            this.resultReasonList = resp.data.list.filter(item => {
                                return item.status === 0;
                            });
                            if(this.resultReasonList.length === 0) {
                                this.$notify({
                                    title: '提示',
                                    message: '保存成功',
                                    type: 'success',
                                    duration: 2000
                                });
                                setTimeout(() => {
                                    this.$router.push({
                                        path: '/student/active-goods-verify'
                                    });
                                }, 500);
                            } else {
                                this.resultDialog = true;
                            }
                        } else {
                            this.$notify({
                                title: '提示',
                                message: resp.msg,
                                duration: 2000,
                                type: 'warning'
                            });
                        }
                    });
                }
            });
        },

        /**
         * 删除商品
         * @param index
         */
        handleDelete(index) {
            this.$confirm('此操作将删除该商品, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.ruleForm.tableData.splice(index, 1);
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            });
        },

        /**
         * 获取商品团购价格列表
         * @param row
         * @param product
         */
        getGroupPrice(row, product) {

            let discountList = row.wholesale_info.list;
            let spec_info = '';

            // 规格处理
            product.spec_list.forEach(spec => {
                spec_info += `${spec.spec_name}:${spec.spec_value}； `;
            });

            let result = [{
                spec_list: spec_info,
                goods_price: product.product_price,
                data: discountList
            }];

            this.$refs.groupPriceDialog.show(result);
        },

        /**
         * 显示设置弹窗
         */
        showSettingDialog() {
            let goodsList = this.ruleForm.tableData;
            let check_list = [];

            goodsList.map(item => {
                item.product_list.map(subItem => {
                    if(subItem.check_status === 1) {
                        check_list.push(subItem);
                    }
                });
            });

            if(!check_list.length) {
                this.$message.warning('未选中任何规格');
                return;
            }

            this.selection = check_list;
            this.settingDialog = true;

        },
        /**
         * 批量设置
         */
        handleBatchSetting() {

            this.$refs.settingForm.validate((valid) => {
                if (valid) {
                    this.ruleForm.tableData.forEach((item,index) => {
                        item.product_list.forEach(subItem => {
                            if(this.selection.includes(subItem)) {
                                subItem.activity_price = this.settingForm.activity_price;
                                this.$set(this.ruleForm.tableData, index, item);
                            }
                        });
                    });

                    this.settingDialog = false;
                }
            });
        },

        /**
         * 全选/取消全选
         */
        handleSelectAll() {
            let goodsList = this.ruleForm.tableData;
            let sku_list = [];
            let check_list = [];

            goodsList.map(item => {
                item.product_list.map(subItem => {
                    subItem.check_status = this.isSelectAll ? 0 : 1;
                    sku_list.push(subItem);
                    if(subItem.check_status === 1) {
                        check_list.push(subItem);
                    }
                });
            });
            this.isSelectAll = sku_list.length === check_list.length;
        },
        /**
         * 选中状态改变
         */
        handleSelectChange() {
            let goodsList = this.ruleForm.tableData;
            let sku_list = [];
            let check_list = [];

            goodsList.map(item => {
                item.product_list.map(subItem => {
                    sku_list.push(subItem);
                    if(subItem.check_status === 1) {
                        check_list.push(subItem);
                    }
                });
            });

            this.isSelectAll = sku_list.length === check_list.length;
        },

        /**
         * 弹窗关闭事件
         */
        handleDialogClose() {
            this.settingForm.activity_price = '';
        },

        /**
         * 点击禁用的input
         * @param row
         * @param rowIndex
         * @param index
         */
        clickDisableInput(row, rowIndex, index) {
            if(!row.product_list[index].check_status) {
                this.$message.warning('请勾选该规格');
            }
        },
    }
};
</script>

<style scoped lang="less">

.wrapper {
    width: 100%;
    position: relative;
    background: #fff;
    box-sizing: border-box;

    .page {
        width: 100%;
        height: calc(100% - 60px);
        background: #fff;
        display: flex;
        flex-direction: column;
        /*header*/

        .header {
            height: 68px;
            padding: 24px;
            box-sizing: border-box;
            box-shadow: 0px -1px 0px 0px #F0F2F5;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #F0F2F5;

            .header-title {
                color: #333333;
                font-size: 20px;
                height: 20px;
                font-weight: 500;
                position: relative;
                margin: 24px 0 24px 12px;

                &::before {
                    content: '';
                    position: absolute;
                    left: -8px;
                    top: -1px;
                    width: 3px;
                    height: 20px;
                    background: #1890FF;
                }
            }
        }

        .btn-group {
            text-align: center;
            margin-top: 24px;

            .el-button {
                margin: 0 24px;
            }
        }

        .table-item {
            margin: 28px 0;
            height: 30px;
        }
    }
    /deep/ .el-dialog {
        margin-top: 15vh!important;
        .el-dialog__header {
            padding-top: 10px;
            box-shadow: 0 1px 0 0 rgba(233, 233, 233, 1);
            display: flex;
            align-items: center;
            background: #FAFAFA;
            border-radius: 4px 4px 0 0;

            .el-dialog__title {
                font-weight: 500;
                color: #333;
                font-size: 14px;
            }

            .el-icon-close:before {
                color: rgb(194, 194, 194);
                font-size: 17px;
                font-weight: bold;
            }

            .el-dialog__headerbtn {
                top: 14px;
            }
        }

        .el-dialog__body {
            padding: 24px 24px 0;
        }

        .el-textarea__inner {
            resize: none;
        }

        .el-dialog__footer {
            text-align: center;
            padding-bottom: 30px;
            margin-top: 6px;
        }
    }
}

/* 字体高亮 */
.cursor-font {
    color: rgb(64, 158, 255);
    cursor: pointer;
}
.reduction_price {
    color: #FF3030;
    font-size: 14px;
    box-sizing: border-box;
    border: 1px #FF3030 solid;
    border-radius: 4px;
    padding: 7px 5px;
}

/*结果弹窗*/
/deep/ .result-dialog {
    min-height: 240px;
    .result-view {
        display: flex;
        flex-direction: column;
        align-items: center;
        .result-icon {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            margin-bottom: 14px;
            i {
                font-size: 48px;
                margin: 16px 0 12px;
            }
            .el-icon-success {
                color: #2FBDB3;
            }
            .el-icon-error {
                color: #F56C6C;
            }
        }
        .result-reason {
            width: 100%;
            display: flex;
            flex-direction: column;
            margin-bottom: 14px;
            .reason-label {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #333333;
                margin-bottom: 16px;
            }
            .reason-value {
                font-size: 12px;
                font-weight: 400;
                color: #999999;
                line-height: 14px;
                margin-bottom: 10px;
            }
            .reason-list {
                max-height: 300px;
                overflow-y: auto;
            }
        }
    }
    .el-dialog__header {
        display: none!important;
    }
    .el-dialog__body {
        overflow: hidden!important;
    }
}
</style>
